package com.itheima.service;


import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
@Component("securityUserService")
public class SecurityUserService implements UserDetailsService {

    private HashMap map = new HashMap();

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     *
     * @param s username即登录界面用户提交的用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //初始化map,将map作为数据库来使用
        intData();

        //当用户登录时,将用户的username传递进来
        User user = (User) map.get(s);

        //创建一个集合存储角色与权限
        ArrayList<GrantedAuthority> list = new ArrayList<>();
        list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        list.add(new SimpleGrantedAuthority("add"));

        //声明使用明文密码
        //String password = "{noop}" + user.getPassword();

        //将用户名,密码和权限授权对象封装到security框架提供的User中
        org.springframework.security.core.userdetails.User detailUser = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), list);

        return detailUser;
    }

    //模仿数据库
    private void intData() {
        User user1 = new User();
        user1.setUsername("zhangsan");
        user1.setPassword(bCryptPasswordEncoder.encode("123456"));

        User user2 = new User();
        user2.setUsername("lisi");
        user2.setPassword(bCryptPasswordEncoder.encode("123456"));

        map.put(user1.getUsername(),user1);
        map.put(user2.getUsername(),user2);

    }

   /**public static void main(String[] args) {

        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode1 = bCryptPasswordEncoder.encode("123");
        String encode2 = bCryptPasswordEncoder.encode("123");
        System.out.println(encode1);
        System.out.println(encode2);

        //使用明文密码和加密后的密码进行匹配
        System.out.println(bCryptPasswordEncoder.matches("123",encode2));
        System.out.println(bCryptPasswordEncoder.matches("123",encode1));
    }*/
}
